<?php

// -----------------------------------------------------------------------------

if (!isset($_GET['date'])) {
    exit("需要传入有效的参数。");
}

// -----------------------------------------------------------------------------

require 'global/functions.php';
include "config/config.php";
include "DBManager.php";
include "global/globalAuth.php";
include "createDBIfNotExists.php";

// -----------------------------------------------------------------------------

// 设置时区
ini_set('date.timezone', $timezone);

$date = $_GET['date']; // 传入的日期
$preday = getTheDate($date, "-", "1"); // 前一天
$nextday = getTheDate($date, "+", "1"); // 后一天
$today = date('Y-m-d'); // 今天

// -----------------------------------------------------------------------------

$db = new DBManager($dbPath);

// 当日新建的记忆片段
$content = $db->readFromTable($date);

// -----------------------------------------------------------------------------

function isWord($str)
{
    $word = trim($str);
    $pattern = "/^[A-Za-z\-' ]+$/";

    if (preg_match($pattern, $str)) {
        return true;
    } else {
        return false;
    }

}

// -----------------------------------------------------------------------------

?>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>记忆片段</title>
    <link rel="stylesheet" href="resources/bootstrap-4.3.1-dist/css/bootstrap.min.css">
    <style>
        .clickable {
            cursor: pointer;
        }
    </style>
</head>
<body>

<!-- ----------------------------------------------------------------------- -->

<?php
include 'global/globalNavBar.php';
?>

<!-- ----------------------------------------------------------------------- -->

<!--container-->
<div class="container">

<!-- ----------------------------------------------------------------------- -->
    <div class="card mt-2 mb-2">
        <div class="card-header">
        日期：<?php echo $date; ?> <a href="edit.php?from=create&dateCreate=<?php echo $date; ?>" class="badge badge-pill badge-danger">新建</a>
        <a href="viewByDate.php?date=<?php echo $preday; ?>" class="badge badge-pill badge-info">前一天</a>
        <a href="viewByDate.php?date=<?php echo $nextday; ?>" class="badge badge-pill badge-info">后一天</a>
        <a href="viewByDate.php?date=<?php echo $today; ?>" class="badge badge-pill badge-info">今天</a>
        <div id="copyall" href="#" class="clickable badge badge-pill badge-primary">复制所有</div>
        <div id="openAll" class="clickable badge badge-pill badge-primary">展开所有</div>
        <div id="closeAll" class="clickable badge badge-pill badge-primary">折叠所有</div>
        </div>
    </div>

<!-- ----------------------------------------------------------------------- -->

    <!--当日新建的记忆片段-->
    <div class="card mt-2 mb-2">

        <div class="card-header text-info">

            【类型】：今日首次记忆<br />
            【日期】：<?php echo $date; ?> <a href="listReviewDates.php?date=<?php echo $date; ?>" class="badge badge-pill badge-primary">所有复习日期</a><br />
            【内容】：<div class="clickable copyContent badge badge-pill badge-primary">复制</div> <a href="edit.php?from=edit&dateCreate=<?php echo $date; ?>" class="badge badge-pill badge-primary">编辑</a> <a href="#" onclick="deleteConfirm('<?php echo $date; ?>')" class="badge badge-pill badge-secondary">删除</a> <div class="clickable toggleContent badge badge-pill badge-primary">展开/折叠</div>

        </div>

        <div class="card-body">

            <?php if (empty($content)): ?>

                <div>
                    今日暂无记忆片段，【<a href="edit.php?from=create&dateCreate=<?php echo $date; ?>">新建</a>】一个吧。
                </div>

            <?php else: ?>

                <?php
                    $arr = explode(PHP_EOL, $content);
                    if (is_array($arr)) {
                        foreach ($arr as $value) {
                            $value = trim($value);
                            if (isWord($value)) {
                                $url = $dict . $value;
                                echo <<<BBB
                                    <a href="$url" class="text-decoration-none">$value</a>
                                    <br />
                                BBB;
                            } else {
                                echo $value;
                                echo "<br />";
                            }
                        }
                    }
                ?>

            <?php endif; ?>

        </div>

    </div>
    <!--当日新建的记忆片段-->

<!-- ----------------------------------------------------------------------- -->


<?php

/* 取得当日所有复习日期 */

$fuxiLunci = 1; // 复习轮次
$fuxiDates = []; // 当日所有复习日期

while($fuxiLunci <= $reviewTimes) {
    $fuxiDates[] = getTheDate($date, "-", pow(2,($fuxiLunci - 1)));
    $fuxiLunci += 1;
}

/* 打印当日所有复习内容 */

$fuxiLunci = 1;
foreach ($fuxiDates as $fuxiDate) {

    $fuxiContent = $db->readFromTable($fuxiDate);
    $html = "";

    if (is_string($fuxiContent)) {

        $arr = explode(PHP_EOL, $fuxiContent);
        if (is_array($arr)) {
            foreach ($arr as $value) {
                $value = trim($value);
                if (isWord($value)) {
                    $url = $dict . $value;
                    $html .= <<<BBB
                        <a href="$url" class="text-decoration-none">$value</a>
                        <br />
                    BBB;
                } else {
                    $html .= <<<BBB
                        $value
                        <br />
                    BBB;
                }
            }
        }

    }

    if (!empty($html)) {
        echo <<<BBB

            <div class="card mt-2 mb-2">

                <div class="card-header">
                    【类型】：复习<br />
                    【首记日期】：$fuxiDate<br />
                    【复习轮次】：$fuxiLunci <a href="listReviewDates.php?date=$fuxiDate" class="badge badge-pill badge-primary">所有复习轮次</a><br />
                    【内容】：<div class="clickable copyContent badge badge-pill badge-primary">复制</div> <a href="edit.php?from=edit&dateCreate=$fuxiDate" class="badge badge-pill badge-primary">编辑</a> <a href="#" onclick="deleteConfirm('$fuxiDate')" class="badge badge-pill badge-secondary">删除</a> <div class="clickable toggleContent badge badge-pill badge-primary">展开/折叠</div>
                </div>

                <div class="card-body">
                    {$html}
                </div>
                
            </div>

        BBB;
    }

    $fuxiLunci += 1;

}

?>

<!-- ----------------------------------------------------------------------- -->

</div>
<!--container-->

<!-- ----------------------------------------------------------------------- -->

<!-- Modal -->
<!-- 确认删除 -->
<div class="modal fade" id="modalConfirmDelete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">确认要删除吗？</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <div class="modal-body">

                <div class="mt-2">
                    <p>该操作无法撤销，请谨慎选择。</p>
                </div>

            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">取消</button>
                <button id="btnSureToDelete" type="button" class="btn btn-outline-primary">确定</button>
            </div>

        </div>
    </div>
</div>

<!-- ----------------------------------------------------------------------- -->

<script src="resources/jquery/jquery-3.4.0.min.js"></script>
<script src="resources/bootstrap-4.3.1-dist/js/bootstrap.min.js"></script>

<!-- ----------------------------------------------------------------------- -->

<script>
    // 将指定的字符串写入剪切板中
    function copyToClipboard(str) {
        var $temp = $("<textarea>");
        $("body").append($temp);
        $temp.val(str).select();
        document.execCommand("copy");
        $temp.remove();
    }
</script>

<!-- ----------------------------------------------------------------------- -->

<script>
    // 点击复制所有按钮时执行的动作
    $("#copyall").click(function () {
        var words = "";
        $(".card-body").each(function() {
            words = words + this.outerText + '\r\n\r\n';
        });

        copyToClipboard(words);
    });
</script>

<!-- ----------------------------------------------------------------------- -->

<script>
    // 复制指定日期的记忆片段
    $(".copyContent").click(function () {
        // 参考：https://stackoverflow.com/questions/5744207/jquery-outer-html/5744268#5744268
        var str = $(this).parent().next().prop('outerText');
        copyToClipboard(str);
    });
</script>

<!-- ----------------------------------------------------------------------- -->

<script>
    $(".toggleContent").click(function () {
        var targetElement = $(this).parent().next()
        if (targetElement.is(":hidden")) {
            targetElement.slideDown("fast")
        } else {
            targetElement.slideUp("fast")
        }
    })
</script>

<!-- ----------------------------------------------------------------------- -->

<script>
    // 展开所有
    $("#openAll").click(function () {
        $(".card-body").slideDown("fast")
    })

    // 折叠所有
    $("#closeAll").click(function () {
        $(".card-body").slideUp("fast")
    })
</script>

<!-- ----------------------------------------------------------------------- -->

<script src="resources/vanilla-back-to-top/vanilla-back-to-top.min.js"></script>
<script>
    addBackToTop({
        zIndex: 2000,
        diameter: 56,
        scrollDuration: 300,
        backgroundColor: 'rgb(255, 82, 82)',
        textColor: '#fff'
    })
</script>

<!-- ----------------------------------------------------------------------- -->

<script>
    var dateToDelete = ""

    function deleteConfirm(date) {
        dateToDelete = date
        $("#modalConfirmDelete").modal("show")
    }

    $("#btnSureToDelete").click(function () {

        $("#modalConfirmDelete").modal("hide")
        var url = "DBDeleteContent.php?date=" + dateToDelete

        var request = $.ajax({
            url: url,
            method: "GET",
            dataType: "html"
        });

        request.done(function(msg) {
            alert(msg)
            document.location.reload()
        });

        request.fail(function(jqXHR, textStatus) {
            alert( "请求失败：" + textStatus );
        });

    })
</script>

<!-- ----------------------------------------------------------------------- -->

<script>

    // 快捷键
    var keyGPressed = 0;
    $(window).keydown(function(event){

        keyPressed = (String.fromCharCode(event.which).toLowerCase())

        // 查看更多 keycode，参考：
        // https://www.toptal.com/developers/keycode

        switch (event.keyCode) {
            case 37:
                // 左方向键，查看前一日日程
                keyGPressed = 0;
                window.open("viewByDate.php?date=<?php echo $preday; ?>", "_self");
                break
            case 39:
                // 右方向键，查看后一日日程
                keyGPressed = 0;
                window.open("viewByDate.php?date=<?php echo $nextday; ?>", "_self");
                break
            case 48:
                // 主键盘数字键 0，查看今日日程
                keyGPressed = 0;
                window.open("viewByDate.php?date=<?php echo $today; ?>", "_self");
                break
            case 96:
                // 小键盘数字键 0，查看今日日程
                keyGPressed = 0;
                window.open("viewByDate.php?date=<?php echo $today; ?>", "_self");
                break
        }

        switch (keyPressed) {
            case "i":
                // 进入编辑
                keyGPressed = 0;
                window.open("<?php echo 'edit.php?from=edit&dateCreate=' . $date; ?>", "_self");
                break
            case "g":
                // 返回顶部
                if (keyGPressed == 1) {
                    $("html, body").animate({ scrollTop: 0});
                    keyGPressed = 0
                } else {
                    keyGPressed = 1
                }
                break
            case "j":
                keyGPressed = 0;
                // 屏幕向下滚动一小段距离
                var y = $(window).scrollTop();
                $('html, body').animate({ scrollTop: y + 650})
                break;
            case "k":
                keyGPressed = 0;
                // 屏幕向上滚动一小段距离
                var y = $(window).scrollTop();
                $('html, body').animate({ scrollTop: y - 650})
                break;
            default:
                keyGPressed = 0;
                break;
        }

        // 滚动到屏幕底部
        if (event.shiftKey) {
            switch (String.fromCharCode(event.which).toLowerCase()) {
                case 'g':
                    keyGPressed = 0;
                    $("html, body").animate({ scrollTop: $(document).height() }, 1000);
                    break
            }
        }

    })

</script>

<!-- ----------------------------------------------------------------------- -->

</body>
</html>
